import React, { useState, useEffect } from 'react';
import { Product } from '../types';
import './STYLE/products.css'
import axios from 'axios'
import debounce from 'lodash.debounce';
// 新增：模态框组件
interface ProductModalProps {
  visible: boolean;
  product: Product | null;
  onClose: () => void;
  onSave: (product: Product) => void;
  categories: string[];
}

const ProductModal: React.FC<ProductModalProps> = ({ visible, product, onClose, onSave, categories }) => {
  const [form, setForm] = useState<Product>(
    product || { id: 0, name: '', price: 0, stock: 0, category: '', brand: '', description: '', image: '' }
  );
  const [step, setStep] = useState(1);
  const [showTip, setShowTip] = useState(false);
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{[k: string]: string}>({});

  React.useEffect(() => {
    if (product) setForm(product);
    setStep(1);
  }, [product]);

  if (!visible) return null;

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: name === 'price' || name === 'stock' ? Number(value) : value }));
  };

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files && e.target.files[0];
    if (file) {
      const url = URL.createObjectURL(file);
      setForm(prev => ({ ...prev, image: url }));
    }
  };

  const handleNext = () => {
    if (!canNext()) {
      setShowTip(true);
      return;
    }
    setShowTip(false);
    setStep(s => s + 1);
  };
  const handlePrev = () => setStep(s => s - 1);

  // 校验函数
  const validate = () => {
    const errs: {[k: string]: string} = {};
    if (!form.name.trim()) errs.name = '商品名称必填';
    if (!form.price || form.price <= 0) errs.price = '价格需为正数';
    if (!form.stock || form.stock < 0) errs.stock = '库存不能为负数';
    if (!form.brand.trim()) errs.brand = '品牌必填';
    if (!form.description.trim()) errs.description = '简介必填';
    if (!form.category.trim()) errs.category = '类属必选';
    if (!form.image) errs.image = '请上传图片';
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  // 提交时校验并与后端连接
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setLoading(true);
    try {
      if (product && product.id) {
        // 编辑
        await axios.put(`http://localhost:3000/YJL/update/${product.id}`, form);
      } else {
        // 新增
        await axios.post('http://localhost:3000/YJL/add', form);
      }
      setLoading(false);
      onSave(form); // 通知父组件刷新
    } catch {
      setLoading(false);
      setErrors({ submit: '保存失败，请重试' });
    }
  };

  // 关闭时重置
  const handleClose = () => {
    setForm(product || { id: 0, name: '', price: 0, stock: 0, category: '', brand: '', description: '', image: '' });
    setErrors({});
    setShowTip(false);
    onClose();
  };

  // 校验当前步骤是否可跳转下一步
  const canNext = () => {
    if (step === 1) {
      return (
        form.name.trim() &&
        form.price > 0 &&
        form.stock >= 0 &&
        form.brand.trim() &&
        form.description.trim() &&
        form.category.trim()
      );
    }
    if (step === 2) {
      return !!form.image;
    }
    return true;
  };

  return (
    <div className="modal-overlay">
      <div className="modal-content">
        <h2>商品信息 {step === 1 ? '（1/3 填写信息）' : step === 2 ? '（2/3 上传图片）' : '（3/3 确认提交）'}</h2>
        <form onSubmit={handleSubmit}>
          {errors.submit && <div className='form-error'>{errors.submit}</div>}
          {showTip && (
            <div style={{ color: 'red', marginBottom: 10 }}>请完成当前页所填项</div>
          )}
          {step === 1 && (
            <>
              <label>商品名称：<input name="name" value={form.name} onChange={handleChange} required />{errors.name && <div className='form-error'>{errors.name}</div>}</label>
              <label>价格：<input name="price" type="number" value={form.price} onChange={handleChange} required />{errors.price && <div className='form-error'>{errors.price}</div>}</label>
              <label>库存：<input name="stock" type="number" value={form.stock} onChange={handleChange} required />{errors.stock && <div className='form-error'>{errors.stock}</div>}</label>
              <label>品牌：<input name="brand" value={form.brand} onChange={handleChange} required />{errors.brand && <div className='form-error'>{errors.brand}</div>}</label>
              <label>简介：<textarea name="description" value={form.description} onChange={handleChange} required />{errors.description && <div className='form-error'>{errors.description}</div>}</label>
              <label>类属：
                <select name="category" value={form.category} onChange={handleChange} required>
                  <option value="">请选择</option>
                  {categories.map(c => (
                    <option key={c} value={c}>{c}</option>
                  ))}
                </select>
                {errors.category && <div className='form-error'>{errors.category}</div>}
              </label>
            </>
          )}
          {step === 2 && (
            <>
              <label>图片上传：
                <input type="file" accept="image/*" onChange={handleImageChange} />
                {errors.image && <div className='form-error'>{errors.image}</div>}
              </label>
              {form.image && (
                <div style={{ marginBottom: 12 }}>
                  <img src={form.image} alt="预览" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 8 }} />
                  <button type="button" onClick={() => setForm(f => ({ ...f, image: '' }))}>重新上传</button>
                </div>
              )}
            </>
          )}
          {step === 3 && (
            <div style={{ fontSize: '15px' }}>
              <div><b>商品名称：</b>{form.name}</div>
              <div><b>价格：</b>{form.price}</div>
              <div><b>库存：</b>{form.stock}</div>
              <div><b>品牌：</b>{form.brand}</div>
              <div><b>简介：</b>{form.description}</div>
              <div><b>类属：</b>{form.category}</div>
              <div><b>图片：</b>{form.image && <img src={form.image} alt="预览" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 8 }} />}</div>
            </div>
          )}
          <div className="modal-actions">
            {step > 1 && <button type="button" className="btn" onClick={handlePrev} disabled={loading}>上一步</button>}
            {step < 3 && <button type="button" className="btn btn-primary" onClick={handleNext} disabled={!canNext() || loading}>下一步</button>}
            {step === 3 && <button type="submit" className="btn btn-primary" disabled={loading}>{loading ? '提交中...' : '提交'}</button>}
            <button type="button" className="btn" onClick={handleClose} disabled={loading}>取消</button>
          </div>
        </form>
      </div>
    </div>
  );
};

const Products: React.FC = () => {
  // 商品数据状态
  const [products, setProducts] = useState<Product[]>([]);

  // 搜索和筛选状态
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [selectedCategory, setSelectedCategory] = useState<string>('');

  // 防抖搜索
  const debouncedSearch = React.useRef(
    debounce((val: string, cat: string) => {
      fetchProducts(val, cat);
    }, 400)
  ).current;

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value);
    debouncedSearch(e.target.value, selectedCategory);
  };

  // 搜索和筛选触发后端拉取
  const handleSearch = () => {
    fetchProducts(searchTerm, selectedCategory);
  };
  const handleCategoryChange = (cat: string) => {
    setSelectedCategory(cat);
    fetchProducts(searchTerm, cat);
  };

  // 分类搜索状态
  const [categorySearch, setCategorySearch] = useState('');
  // 分类搜索防抖
  const debouncedCategorySearch = React.useRef(
    debounce((val: string) => {
      fetchProducts(searchTerm, selectedCategory, val);
    }, 400)
  ).current;
  const handleCategorySearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setCategorySearch(e.target.value);
    debouncedCategorySearch(e.target.value);
  };

  // 新增：模态框状态
  const [modalVisible, setModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  // 新增：图片预览状态
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [previewIndex, setPreviewIndex] = useState<number>(-1);

  // 分类数据状态
  const [categories, setCategories] = useState<string[]>([]);

  // 打开图片预览
  const openImagePreview = (img: string) => {
    const idx = products.findIndex(p => p.image === img);
    setPreviewIndex(idx);
    setImagePreview(img);
  };

  // 切换图片
  const handlePrevImage = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (previewIndex > 0) {
      const prevImg = products[previewIndex - 1].image;
      setPreviewIndex(previewIndex - 1);
      setImagePreview(prevImg);
    }
  };
  const handleNextImage = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (previewIndex < products.length - 1) {
      const nextImg = products[previewIndex + 1].image;
      setPreviewIndex(previewIndex + 1);
      setImagePreview(nextImg);
    }
  };
  // 下载图片
  const handleDownload = async (e: React.MouseEvent) => {
    e.stopPropagation();
    if (imagePreview) {
      try {
        const response = await fetch(imagePreview, { mode: 'cors' });
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'product-image.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } catch {
        alert('图片下载失败，可能是跨域问题');
      }
    }
  };

  // 后端已处理过滤，products即为当前筛选结果
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 5;
  const totalPages = Math.ceil(products.length / pageSize);
  const paginatedProducts = products.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  // 选中状态
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const allSelected = paginatedProducts.length > 0 && paginatedProducts.every(p => selectedIds.includes(p.id));
  const someSelected = paginatedProducts.some(p => selectedIds.includes(p.id));

  // 全选/反选处理
  const handleSelectAll = () => {
    if (allSelected) {
      setSelectedIds(selectedIds.filter(id => !paginatedProducts.some(p => p.id === id)));
    } else {
      setSelectedIds([
        ...selectedIds,
        ...paginatedProducts.filter(p => !selectedIds.includes(p.id)).map(p => p.id)
      ]);
    }
  };

  // 单个复选框处理
  const handleSelect = (id: number) => {
    setSelectedIds(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]);
  };

  // 已移除待审核复选框相关变量

  // 获取商品数据的方法（带参数，支持分类模糊搜索）
  const fetchProducts = async (search = '', category = '', categoryLike = '') => {
    try {
      const res: any = await axios.get('http://localhost:3000/YJL/datalist', {
        params: { search, category, categoryLike }
      });
      if (res.data && Array.isArray(res.data.data)) {
        setProducts(res.data.data);
        console.log(res.data)
      }
    } catch (err) {
      // 可以加个错误提示
      console.error('获取商品数据失败', err);
    }
  };

  // 获取分类数据
  const fetchCategories = async () => {
    try {
      const res: any = await axios.get('http://localhost:3000/YJL/categories');
      if (res.data && Array.isArray(res.data.data)) {
        setCategories(res.data.data);
      }
    } catch (err) {
      console.error('获取分类失败', err);
    }
  };

  useEffect(() => {
    fetchProducts();
    fetchCategories();
  }, []);

  // 处理编辑
  const handleEdit = (id: number) => {
    const product = products.find(p => p.id === id) || null;
    setEditingProduct(product);
    setModalVisible(true);
  };

  // 处理删除
  const handleDelete = (id: number) => {
    if (window.confirm('确定要删除这个商品吗？')) {
      setProducts(products.filter(product => product.id !== id));
    }
  };

  // 处理添加商品（实际项目中会跳转到添加页面或打开模态框）
  const handleAdd = () => {
    setEditingProduct({ id: Date.now(), name: '', price: 0, stock: 0, category: '', brand: '', description: '', image: '', pending: false });
    setModalVisible(true);
  };

  // 新增：保存编辑
  const handleSave = (updated: Product) => {
    setProducts(prev => {
      const exists = prev.some(p => p.id === updated.id);
      if (exists) {
        return prev.map(p => (p.id === updated.id ? updated : p));
      } else {
        return [...prev, updated];
      }
    });
    setModalVisible(false);
    setEditingProduct(null);
  };

  // 新增：关闭模态框
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingProduct(null);
  };

  // 翻页处理
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <div className="page-container">
      <h1>商品管理</h1>
      <div className="actions-bar">
        <button className="btn btn-primary" onClick={handleAdd}>
          添加商品
        </button>

        <div className="search-box" style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
          <input
            type="text"
            placeholder="搜索商品..."
            value={searchTerm}
            onChange={handleInputChange}
            style={{ flex: 1 }}
          />
          <button onClick={handleSearch}>搜索</button>
          <select
            value={selectedCategory}
            onChange={(e) => handleCategoryChange(e.target.value)}
            className="category-select"
            style={{ width: 160, minWidth: 120 }}
          >
            <option value="">所有分类</option>
            {categories.map(c => (
              <option key={c} value={c}>{c}</option>
            ))}
          </select>
        </div>
        <div className="search-box">
          <input
            type="text"
            placeholder="分类模糊搜索..."
            value={categorySearch}
            onChange={handleCategorySearchChange}
          />
        </div>

      </div>

      <div className="table-container">
        <table className="product-table">
          <thead>
            <tr>
              <th>
                <input
                  type="checkbox"
                  checked={allSelected}
                  ref={el => { if (el) el.indeterminate = !allSelected && someSelected; }}
                  onChange={handleSelectAll}
                />
              </th>
              <th>ID</th>
              <th>商品名称</th>
              <th>价格</th>
              <th>库存</th>
              <th>品牌</th>
              <th>简介</th>
              <th>类属</th>
              <th>参照图</th>
              <th>待审核</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {paginatedProducts.map(product => (
              <tr key={product.id}>
                <td>
                  <input
                    type="checkbox"
                    checked={selectedIds.includes(product.id)}
                    onChange={() => handleSelect(product.id)}
                  />
                </td>
                <td>{product.id}</td>
                <td>{product.name}</td>
                <td>¥{product.price.toFixed(2)}</td>
                <td>{product.stock}</td>
                <td>{product.brand}</td>
                <td title={product.description}>
                  {product.description.length > 10
                    ? `${product.description.substring(0, 10)}...`
                    : product.description}
                </td>
                <td>{product.category}</td>
                <td>
                  {product.image ? (
                    <img
                      src={product.image}
                      alt={product.name}
                      className="product-thumbnail"
                      style={{ cursor: 'pointer' }}
                      onClick={() => openImagePreview(product.image)}
                    />
                  ) : '无图'}
                </td>
                <td>
                  <span className={product.pending ? 'status-approved' : 'status-pending'}>
                    {product.pending ? '审核通过' : '待审核'}
                  </span>
                </td>
                <td className="table-actions">
                  <button
                    className="btn btn-edit"
                    onClick={() => handleEdit(product.id)}
                  >
                    编辑
                  </button>
                  <button
                    className="btn btn-delete"
                    onClick={() => handleDelete(product.id)}
                  >
                    删除
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {/* 分页控件 */}
      <div className="pagination-bar">
        <button
          className="btn"
          disabled={currentPage === 1}
          onClick={() => handlePageChange(currentPage - 1)}
        >上一页</button>
        {Array.from({ length: totalPages }, (_, i) => (
          <button
            key={i + 1}
            className={`btn${currentPage === i + 1 ? ' btn-primary' : ''}`}
            onClick={() => handlePageChange(i + 1)}
          >{i + 1}</button>
        ))}
        <button
          className="btn"
          disabled={currentPage === totalPages}
          onClick={() => handlePageChange(currentPage + 1)}
        >下一页</button>
      </div>
      <ProductModal
        visible={modalVisible}
        product={editingProduct}
        onClose={handleCloseModal}
        onSave={handleSave}
        categories={categories}
      />
      {/* 图片预览遮罩层 */}
      {imagePreview && previewIndex !== -1 && (
        <div className="image-preview-overlay" onClick={() => { setImagePreview(null); setPreviewIndex(-1); }}>
          <button
            className="image-preview-arrow left"
            onClick={handlePrevImage}
            disabled={previewIndex === 0}
          >&lt;</button>
          <img src={imagePreview} alt="预览" className="image-preview-large" />
          <button
            className="image-preview-arrow right"
            onClick={handleNextImage}
            disabled={previewIndex === products.length - 1}
          >&gt;</button>
          <button className="image-preview-download" onClick={handleDownload}>下载图片</button>
        </div>
      )}
    </div>
  );
};

export default Products;